<?php

namespace App\Http\Controllers\Api\Hpi;

use App\Http\Controllers\ApiController;
use App\Http\Requests\HpiSubStoreRequest;
use App\Models\DrugDictionary;
use App\Models\MedicalFollowUp;
use App\Models\MedicalHpiSub;
use App\Project\Filters\HpiSubFilter;
use Carbon\Carbon;

use App\Project\Transform;
use Illuminate\Http\Request;

class HpiSubController extends ApiController
{
    /**
     * 现病史组项目存储
     * @param \App\Http\Requests\HpiSubStoreRequest $request
     * @param \App\Models\MedicalHpiSub $hpiSub
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(HpiSubStoreRequest $request, MedicalHpiSub $hpiSub)
    {

        $record_id = $request->input('record_id');

        $subs = $hpiSub->where(['record_id' => $record_id])->get(['record_id']);

        if ($subs->count() > 1) {
            return $this->setMessage('没有编辑权限')->setCode('400004')->response();
        }

        $input = (new HpiSubFilter($request))->except('record_id');
        if (isset($input['started_at']) && !empty($input['started_at'])) {
            $input['started_at'] = Carbon::parse($input['started_at'])->startOfMonth()->toDateString();
        } else {
            $input['started_at'] = Carbon::now()->startOfMonth()->toDateString();
        }
        if ($subs->count() === 1) {
            $input = (new Transform())->setArray($input)
                ->convertArrayToString(['symptoms', 'diagnose'])
                ->convertArrayToJson([
                    'medication',
                    'cn_medication',
                    'before_treatment',
                    'after_treatment'
                ])->get();

            $result = MedicalHpiSub::where(['record_id' => $record_id])->update($input);

            return $this->response(['result' => $result]);
        } else {

            $result = $hpiSub->create(array_merge($input, ['record_id' => $record_id]));

            MedicalFollowUp::create(['record_id' => $record_id]);

            return $this->response(['id' => $result['id']]);
        }
    }

    /**
     * 现病史组信息
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function edit(Request $request)
    {
        $data = null;
        $record_id = $request->get('record_id');

        if ($record_id > 0) {

            $data = MedicalHpiSub::select(['id', 'started_at', 'symptoms', 'medication'])
                ->where(['record_id' => $record_id])->get();
        } else {
            abort(400, '缺失病历ID');
        }

        if (is_null($data)) {
            return $this->hasNoData();
        }

        $names = $data->pluck('medication.*.name')->flatten()->unique();

        if ($names->count()) {
            $drugs = DrugDictionary::select(['name', 'is_insulin'])
                ->whereIn('name', $names)
                ->groupBy('name')
                ->get()->pluck('is_insulin', 'name');

            $data->map(function (MedicalHpiSub $sub) use ($drugs) {
                $sub->medication = collect($sub->medication)->map(function ($medication) use ($drugs) {
                    $medication['is_insulin'] = $drugs->get($medication['name']);

                    return $medication;
                });

                return $sub;
            });
        }

        return $this->response($data->toArray());
    }
}
